package com.kx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kx.bean.Car;
import com.kx.bean.Toll;
import com.kx.bean.User;
import com.kx.dao.CarMapper;
import com.kx.dao.TollMapper;
import com.kx.dao.UserMapper;
import com.kx.service.TollService;
import com.kx.vo.DataVO;
import com.kx.vo.TollVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TollServiceImpl implements TollService {

    @Autowired
    private TollMapper tollMapper;

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public DataVO<TollVO> findData(Integer page, Integer limit) {
        DataVO<TollVO> dataVO = new DataVO<>();
        //1、设置code
        dataVO.setCode(0);
        //2、设置msg
        dataVO.setMsg("");
        //3、设置count(如果使用了mybatis-plus分页，则不需要调用其中selectCount方法单独调用)
        IPage<Toll> tollIPage = new Page<>(page, limit);
        IPage<Toll> result = tollMapper.selectPage(tollIPage, null);
        dataVO.setCount(result.getTotal());
        List<Toll> tollList = result.getRecords();

        List<TollVO> tollVOList = new ArrayList<>();
        for (Toll toll : tollList) {
            TollVO tollVO = new TollVO();
            BeanUtils.copyProperties(toll, tollVO);

            QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cid", toll.getCid());
            Car car = carMapper.selectOne(queryWrapper);
            tollVO.setCph(car.getLicensePlate());
            tollVOList.add(tollVO);
        }
        //4、设置data
        dataVO.setData(tollVOList);
        return dataVO;
    }

    @Override
    public List<Toll> findOrdersByUid(Integer uid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid);
        User user = userMapper.selectOne(queryWrapper);
        QueryWrapper<Toll> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("cid", user.getCid());
        return tollMapper.selectList(queryWrapper1);
    }

    @Override
    public int deleteById(Integer fid) {
        return tollMapper.deleteByPrimaryKey(fid);
    }

    @Override
    public int insertToll(Toll toll) {
        return tollMapper.insert(toll);
    }
}
